package cn.aib.eduservice.listener;

import cn.aib.eduservice.entity.EduSubject;
import cn.aib.eduservice.entity.excel.SubjectData;
import cn.aib.eduservice.service.EduSubjectService;
import cn.aib.servicebase.exception.GuliException;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    private EduSubjectService service;

    //无参构造
    public SubjectExcelListener(){}

    //有参构造，将service注入进来，方便查询数据库
    public SubjectExcelListener(EduSubjectService service){
        this.service = service;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        //判断subjectData是否空，空抛出异常
        if(subjectData == null){
            throw new GuliException(20001, "数据为空");
        }
        //保证课程分类不能出现重复
        //查询一级分类名称,并判断是否重复
        EduSubject oneSubject = existOneSubject(subjectData.getOneSubjectName(), service);

        if(oneSubject == null){ //空就想表中添加分类数据
            oneSubject = new EduSubject();
            //设置标题
            oneSubject.setTitle(subjectData.getOneSubjectName());
            //设置父分类ID
            oneSubject.setParentId("0");
            //保存分类
            service.save(oneSubject);
        }

        //二级分类的父ID，执行到这一步，表中一定存在其父分类的记录，然后ID会设置到oneSubject，因此直接获取即可
        String pid = oneSubject.getId();
        System.out.println("pid-----------------:"+pid);

        //查询二级分类名称，并判断是否重复
        EduSubject twoSubject = existTwoSubject(subjectData.getTwoSubjectName(), pid, service);

        if(twoSubject == null){ //空就想表中添加二级分类数据
            twoSubject = new EduSubject();
            //设置标题
            twoSubject.setTitle(subjectData.getTwoSubjectName());
            //设置父分类ID
            twoSubject.setParentId(pid);
            //保存分类
            service.save(twoSubject);
        }
    }

    public EduSubject existOneSubject(String subjectName,EduSubjectService service){
        //查询一级的课程分类
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();

        wrapper.eq("title", subjectName);
        wrapper.eq("parent_id", 0);

        EduSubject subject = service.getOne(wrapper);

        return subject;
    }

    public EduSubject existTwoSubject(String subjectName,String pid,EduSubjectService service){
        //查询二级的课程分类
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();

        wrapper.eq("title", subjectName);
        wrapper.eq("parent_id", pid);

        EduSubject subject = service.getOne(wrapper);

        return subject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
